import type { FC, ReactNode } from 'react'
import React, { memo } from 'react'
import { Button, FormInstance, Input, Tag } from 'antd'
import { ActionDesc } from '@/global/constant'
import confirmModal from '@/utils/confirm-modal'
import { fetchPageDeleteAction } from '@/store/module/main/page-common'
import usePageSearch from '@/hooks/use-page-search'
import usePageModal from '@/hooks/use-page-modal'
import usePageContent from '@/hooks/use-page-content'
import PageSearch from '@/components/page-search'
import PageContent from '@/components/page-content'
import PageModal from '@/components/page-modal'
import VerifyCodeButton from '@/components/verify-code-button'
import loginListSearch from './config/loginlist-search'
import loginListContent from './config/loginlist-content'

interface IProps {
  children?: ReactNode
}

const inputWithVerifyCodeStyle = {
  display: 'flex',
  alignItems: 'center'
}

const LoginList: FC<IProps> = (props) => {
  // 通用：modal的确定与取消：主要事件，
  const okCb = async (form: FormInstance | undefined) => {
    // 获取当前配置的信息，看一下是属于什么类型的表单描述
    const { desc } = curModalConfig.formProps
    // 获取表单数据
    const values = form?.getFieldsValue()
    if (desc === ActionDesc.SecondAuth) {
      /** 二次认证 **/
      return toSecondAuth(values)
    }
  }

  const { pageContentRef, searchClick, resetClick } = usePageSearch()
  const { pageModalRef, onModalOk, onModalCancel, getCodeClick } = usePageModal(
    { okCb }
  )
  const {
    modal: [curModalConfig],
    dispatch,
    toSecondAuth,
    handleSecondAuth
  } = usePageContent({ pageModalRef })

  const actionClick = (actionType: any, record?: any) => {
    if (actionType === ActionDesc.Delete) {
      /** 删除 **/
      handleSecondAuth(() => {
        confirmModal('是否删除该日志?').then(() =>
          dispatch(fetchPageDeleteAction(record.logId))
        )
      })
    }
  }

  // 通用：自定义表格内容--渲染自定义的表单项
  const renderTableCpn = (
    text: string | number,
    record: any,
    customkey: string
  ) => {
    if (customkey === 'logStatus') {
      let el
      text === 200 && (el = <Tag color="success">成功</Tag>)
      text !== 200 && (el = <Tag color="red">失败</Tag>)
      return el
    } else if (customkey === 'logTime') {
      return <Button type="link">{text}s</Button>
    } else return <span>{text}</span>
  }
  return (
    <>
      <PageSearch
        config={loginListSearch}
        searchClick={searchClick}
        resetClick={resetClick}
      />
      <PageContent
        ref={pageContentRef}
        config={loginListContent}
        actionClick={actionClick}
      >
        {renderTableCpn}
      </PageContent>
      <PageModal
        ref={pageModalRef}
        modalConfig={curModalConfig}
        onOk={onModalOk}
        onCancel={onModalCancel}
      >
        <div key="code" style={inputWithVerifyCodeStyle}>
          <Input name="code" />
          <VerifyCodeButton onClick={getCodeClick} />
        </div>
      </PageModal>
    </>
  )
}

export default memo(LoginList)
